package top.infopub.security.listener;


import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationListener;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import top.infopub.security.core.CaptchaUsernamePasswordToken;
import top.infopub.security.service.SysUserService;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.SpringContext;


/**
 * 用户登录监听器，实现shiro的AuthenticationListener接口
 * @author Awoke
 * @version 2018年9月17日
 * @see LoginListener
 * @since
 */
public class LoginListener implements AuthenticationListener {

    private static final Logger log = LoggerFactory.getLogger(LoginListener.class);

    @Override
    public void onSuccess(AuthenticationToken token, AuthenticationInfo info) {
        CaptchaUsernamePasswordToken authcToken = (CaptchaUsernamePasswordToken)token;
        @SuppressWarnings("unchecked")
        Collection<String> realms = info.getPrincipals().asList();
        if (realms != null && !realms.isEmpty()) {
            String principal = (String)realms.iterator().next();
            AuthorizationVO auth = SessionUserUtils.getUserFormPrincipal(principal);
            AuthorizationVO authDtl = SpringContext.getBean(SysUserService.class).getUserDetail(
                auth.getId());
            if (authDtl == null) {
                // 把用户信息存放到Session中
                SessionUserUtils.setSessionAttributeForUserDtl(auth);
            }
            else {
                // 把用户详细信息存放到Session中
                SessionUserUtils.setSessionAttributeForUserDtl(authDtl);
            }
            // 调用 登录成功处理函数
            SpringContext.getBean(SysUserService.class).loginSuccess(auth.getId(),
                authcToken.getHost());
            log.info("账号：" + auth.getUserName() + "登录成功，来源IP:" + authcToken.getHost());
        }
    }

    @Override
    public void onFailure(AuthenticationToken token, AuthenticationException ae) {
        try {
            CaptchaUsernamePasswordToken authcToken = (CaptchaUsernamePasswordToken)token;
            SpringContext.getBean(SysUserService.class).loginError(authcToken.getUsername(),
                authcToken.getHost());
            log.info("用户名：{}本次登录失败", authcToken.getUsername());
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void onLogout(PrincipalCollection principals) {
        @SuppressWarnings("unchecked")
        Collection<String> realms = principals.asList();
        if (realms != null && !realms.isEmpty()) {
            String principal = (String)realms.iterator().next();
            AuthorizationVO auth = SessionUserUtils.getUserFormPrincipal(principal);
            SpringContext.getBean(SysUserService.class).logout(auth.getId());
        }
    }

}
